#!/bin/bash
agent="wget -P /home/gs https://repo.zabbix.com/zabbix/4.0/debian/pool/main/z/zabbix-release/zabbix-release_4.0-3+buster_all.deb"
name="zabbix"
cwd=$(cd "$(dirname "$0")";pwd)

install_zabbix() {
sudo groupadd $name
sudo useradd $name -g $name -s /sbin/nologin
#赋予zabbix权限，编辑/etc/sudoers,添加如下内容
sudo bash -c 'echo "zabbix  ALL=(root)    NOPASSWD:/usr/bin/docker,/usr/bin/python,/etc/zabbix/script/docker_discovery.py">>/etc/sudoers'
sudo $agent
sudo dpkg -i /home/gs/zabbix-release_4.0-3+buster_all.deb
sudo apt-get update
#手动降级安装
sudo apt install -y aptitude
sudo aptitude install  zabbix-agent
}
install_zabbix

conf_zabbix() {
#配置zabbix服务端
sudo sed  -i "s/Server=127.0.0.1/Server=192.168.3.40/g" /etc/zabbix/zabbix_agentd.conf
sudo sed  -i "s/ServerActive=127.0.0.1/ServerActive=192.168.3.40/g" /etc/zabbix/zabbix_agentd.conf
sudo sed  -i "s/# UnsafeUserParameters=0/UnsafeUserParameters=1/g" /etc/zabbix/zabbix_agentd.conf
sudo sed  -i "s/# Hostname=/Hostname=db1/g" /etc/zabbix/zabbix_agentd.conf
#添加自定义python监控脚本
sudo bash -c 'cat >>/etc/zabbix/zabbix_agentd.conf<<EOF
UserParameter=docker_discovery[*], python /etc/zabbix/script/docker_discovery.py \$1
UserParameter=docker_stats[*],  sudo /usr/bin/python  /etc/zabbix/script/docker_monitor.py  \$1 \$2
UserParameter=docker_process[*], /bin/bash  /etc/zabbix/script/docker_processmonitor.sh   \$1  \$2  \$3
EOF'
#添加存放目录
sudo mkdir /etc/zabbix/script
sudo cp $cwd/python_zabbix/* /etc/zabbix/script
#设置目录运行权限

sudo chmod 757  /etc/zabbix/script/docker_discovery.py
sudo chmod a+x /etc/zabbix/script/*
sudo chown -R zabbix:zabbix /etc/zabbix/script/

#安装环境支持脚本运行 注意用户权限及安装配置
sudo pip install docker
sudo pip  install  simplejson

}
conf_zabbix
sudo systemctl restart zabbix-agent